package com.chinda.common.utils;


import com.alibaba.fastjson.JSON;
import com.chinda.common.config.jwt.JWTAutoConfiguration;
import com.chinda.common.security.SysUserDetails;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * JWT工具类
 *
 * @author Wang Chinda
 * @date 2020/7/11
 * @see
 * @since 1.0
 */
@Component
@AllArgsConstructor
public class JWTTokenUtil {

    private static JWTAutoConfiguration jwtAutoConfiguration;

    private final JWTAutoConfiguration jwtConfig;

    @PostConstruct
    public void initialize() {
        jwtAutoConfiguration = this.jwtConfig;
    }


    public static String createAccessToken(SysUserDetails userDetails) {
        // 登录成功后生成JWTToken
        return Jwts.builder()
                // 设置用户名和用户id
                .setId(userDetails.getUserId() + "")
                // 主题
                .setSubject(userDetails.getUsername())
                // 签发时间
                .setIssuedAt(new Date())
                // 签发者
                .setIssuer("chinda")
                // 放置用户拥有权限
                .claim("authorities", JSON.toJSONString(userDetails.getAuthorities()))
                // 失效时间
                .setExpiration(new Date(System.currentTimeMillis() + jwtAutoConfiguration.getExpiration()))
                // 签名算法和密钥
                .signWith(SignatureAlgorithm.HS512, jwtAutoConfiguration.getSecret())
                .compact();
    }
}
